package com.xiaoge.demo.pojo.id_generator;

import com.xiaoge.demo.core.ServiceException;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.query.spi.QueryImplementor;
import org.springframework.util.ObjectUtils;

import java.io.Serializable;
import java.util.List;

/**
 * 作者：guoyzh
 * 时间：2018/12/28 8:53
 * 功能：自定义id生成
 */
public class UserIDGenerator implements IdentifierGenerator {

    @Override
    public Serializable generate(SharedSessionContractImplementor implementor, Object o) throws HibernateException {
        String idStr = "U";
        try {
            // 获取最后创建时间插入的id
            QueryImplementor query = implementor.createNativeQuery("select id from user order by id desc limit 1");
            List list = query.getResultList();

            if (ObjectUtils.isEmpty(list)) {
                String result = idStr + String.format("%011d", 1);
                return result;
            } else {
                String lastId = (String) list.get(0);
                String id = lastId.substring(2).trim();
                String result = idStr + String.format("%011d", 1 + Integer.parseInt(id));
                return result;
            }
        } catch (NumberFormatException e) {
            throw new ServiceException("id生成失败");
        }
    }
}
